import React, { useState, useEffect } from 'react';
import { Form, Input, message, Modal, Descriptions, Badge, Button, Divider, InputNumber } from 'antd';
import Nunberinput from '../../../../components/Nunberinput/Nunberinput'
import { getCurrent, getexam, updateAnswer, updateComment, downloads } from '../service'
import axios from 'axios'
import Authorized from '@/utils/Authorized';
import FileViewer from 'react-file-viewer';

const { TextArea } = Input;

const FormItem = Form.Item;

const Personinfo = props => {
  const noMatch = ''

  const [info, setinfo] = useState({});//修改实验成绩和记录,评价的数据

  const [form] = Form.useForm();
  const { modalVisible, onCancel, currentinfo } = props;
  console.log(currentinfo, props)
  const getinfo = async () => {
    if (currentinfo) {
      let res1 = await getCurrent({ id: currentinfo })
      let res2 = await getexam({ id: currentinfo })
      var res
      if (res1 && res2) {
        res = { ...res1.data, ...res2.data }
      }
      if (res) {
        let info = res
        if (info.type == 1) {
          info.type = '高级教师'
        } else if (info.type == 2) {
          info.type = '普通教师'

        } else {
          info.type = '学生'

        }
        setinfo(info)
        console.log(res, info)
      }
    }
  }

  useEffect(() => {
    getinfo()


  }, [props.currentinfo])//监听才执行
  const okHandle = async () => {
    const fieldsValue = await form.validateFields();
    form.resetFields();
    // handleAdd(fieldsValue);
  };
  const savegrade = async (value) => {
    let obj = { id: currentinfo, experimentResult: info.experiment_result, answerResult: info.answer_result }
    if (value) {
      let res = await updateAnswer(obj)
    } else {
      let obj1 = { id: currentinfo, teacherComment: info.teacher_comment }
      let rescomment = await updateComment(obj1)

    }
  };
  const download = async (a) => {
    console.log(a)
    if (!info.attachment_path) {
      message.error('当前用户没有上传文件，无需下载')
      return;

    }
    let filePath = info.attachment_path
    var startIndex = filePath.lastIndexOf(".");
    let types;
    if (startIndex !== -1) {
      let type = filePath.substring(startIndex + 1, filePath.length).toLowerCase();
      if (type == 'pdf') {
        types = 'application/pdf'
      } else {
        types = 'application/msword'
        // 9e90f02c-de09-4272-9220-7022734d421f.docx这个地址必须为域名，不可为ip且80端口，否则无法提取，通过微软进行预览
        if (a==1) {
          window.open(`http://view.xdocin.com/xdoc?_xdoc=http://140.207.154.14:50122/upload/${filePath}`)
          return;
        }
      }
      console.log(type)
    } else {
      return
    }
    let config = {
      headers: {
        // "Content-Type": "arraybuffer",
        'Authorization': `${sessionStorage.getItem('tokenHead')} ${sessionStorage.getItem('token')}`,
      },
      responseType: 'blob'
    }
    axios.get('/admin/downloadAttachment?id=' + currentinfo, config)
      .then(res => {
        console.log(res, 111)
        if (res) {
          let blob = new Blob([res.data], { type: types }
          )
          let objectUrl = URL.createObjectURL(blob)
          window.location.href = objectUrl;
        } else {
          message.error(res.message)
        }

      })
      .catch(error => {
        message.error(`file upload failed.`);
      });
  };
  const formRef = React.createRef();
  // 这个是个在numberinput子组件调用的方法
  const changevalue = (e) => {
    //  子组件调用这方法改变grade的值
    if (!isNaN(e)) {
      info.experiment_result = e;
      setinfo({ ...info })
      console.log(e, info)

    } else {
      info[e.target.name] = e.currentTarget.value;
      setinfo({ ...info })
      console.log(e, info)
    }
  };

  return (
    <Modal
      destroyOnClose
      title="个人成绩界面"
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => onCancel()}
    >
      <Descriptions title="个人信息">
        <Descriptions.Item label="账号">{info.username}</Descriptions.Item>
        <Descriptions.Item label="姓名">{info.name}</Descriptions.Item>
        <Descriptions.Item label="类型">{info.type}</Descriptions.Item>
        <Descriptions.Item label="学号">{info.student_number}</Descriptions.Item>
        <Descriptions.Item label="年纪">
          {info.class_grade}
        </Descriptions.Item>
        <Descriptions.Item label="班级">{info.class_name}</Descriptions.Item>

      </Descriptions>
      <Descriptions title="考试信息">
        <Descriptions.Item label="考试名称">{info.exam_name}</Descriptions.Item>
        <Descriptions.Item label="任课老师" span={2}>{info.exam_teacher}</Descriptions.Item>
        <Descriptions.Item label="实验内容">{info.experiment_name}</Descriptions.Item>
        <Descriptions.Item label="备注">{info.experiment_remark}</Descriptions.Item>

      </Descriptions>
      <Descriptions title="成绩信息">
        <Descriptions.Item label="开始时间">{info.start_time}</Descriptions.Item>
        <Descriptions.Item label="结束时间">{info.end_time}</Descriptions.Item>
        <Descriptions.Item label="用时">{info.exam_time}</Descriptions.Item>
        <Descriptions.Item label="考试成绩">
          <InputNumber min={1}
            onChange={changevalue}
            value={info.experiment_result}
            style={{ width: 80 }}
            formatter={value => `${value}`}
            parser={value => value.replace(/[^\d]/g, '')}
            precision={0} />
          {/* <Nunberinput
            style={{ width: 70 }} value={info.experimentResult} onChange={changevalue} /> */}
        </Descriptions.Item>
        <Descriptions.Item label="实验记录" span={2}>
          <Input placeholder="记录" name='answer_result' value={info.answer_result} onChange={changevalue}
            style={{ width: 180, marginRight: '5px' }} />
          <Authorized authority={['admin', 'admin1']} noMatch={noMatch} >
            <Button type="primary" size='small' onClick={(e = true) => { savegrade(e) }}>保存</Button>
          </Authorized>
        </Descriptions.Item>
        <Descriptions.Item label="完成状态">{info.complete_status == 1 ? '已完成' : '未参加'}</Descriptions.Item>
        <Descriptions.Item label="实验报告" span={2}>
          {/* <a href="http://view.officeapps.live.com/op/view.aspx?src=http://http://140.207.154.14:50124/bug.docx" >预览</a> */}


          {/* <FileViewer
        fileType='docx'
        filePath='http://192.168.88.159:8000/测试bug文档.docx'
       /> */}
          <Divider type="vertical" />

          {/* pdf可以直接在线预览。world是直接下载再打开 */}
          {
            info.attachment_path ? (<><Button type="primary" size='small'>
            <a href='#' onClick={() => { download() }}>下载</a>
          </Button> <Button type="primary" size='small'>
            <a href='#' onClick={() => { download(1) }}>预览</a>
          </Button></>) : (<span style={{color:'blue'}}>没有上传报告</span>)
          }


        </Descriptions.Item>
        <Descriptions.Item label="教师评语" span={3}>

          <TextArea allowClear value={info.teacher_comment} name='teacher_comment' onChange={changevalue} style={{ width: 400, verticalAlign: 'center' }} />
          <span style={{ verticalAlign: 'center' }}> <Button type="primary" size='small' onClick={() => { savegrade() }}>保存</Button></span>
        </Descriptions.Item>

      </Descriptions>
    </Modal>
  );
};

export default Personinfo;
